import prisma from '~~/lib/prisma'
import Joi from 'joi'
import md5 from 'md5'
import { Result } from '~~/lib/helper/result'
export default defineEventHandler(async (event) => {
  const body = await readBody(event)
  const schema = Joi.object({
    nickname: Joi.string().required(),
    password: Joi.string().required(),
    phone: Joi.string().pattern(/^1\d{10}$/),
    avatar: Joi.string().required(),
  })

  try {
    await schema.validateAsync(body)
  } catch (error) {
    console.log('error', error)
    return Result.Error('参数错误！')
  }

  // 密码加密
  let salt = 'salt'
  let password = md5(md5(body.password) + salt)
  try {
    let user = await prisma.user.findFirst({ where: { phone: body.phone } })
    if (user) return Result.Error('此账号已经存在！')
    await prisma.user.create({ data: { ...body, password } })
  } catch (error) {
    return Result.Error('创建用户失败！')
  }
  return Result.Ok(null, 200, '账号注册成功！')
})
